package com.gears_software.sxdc.dccx.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;


import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.InputtipsQuery;
import com.amap.api.services.help.Tip;
import com.gears_software.sxdc.dccx.R;
import com.gears_software.sxdc.dccx.application.DCCXApplication;
import com.gears_software.sxdc.dccx.data.adapter.SearchAdapter;
import com.gears_software.sxdc.dccx.data.finder.IUsualAddressFinder;
import com.gears_software.sxdc.dccx.data.model.AddressList;
import com.gears_software.sxdc.dccx.data.model.ResultModel;
import com.gears_software.sxdc.dccx.data.model.request.RAddAddressModel;
import com.sdsmdg.tastytoast.TastyToast;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.App;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ItemClick;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.rest.spring.annotations.RestService;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import qiu.niorgai.StatusBarCompat;

/**
 * Created by SunMuran on 2017/8/9.
 */
@EActivity(R.layout.activity_compile_address)
public class CompileAddressActivity extends Activity implements AMapLocationListener {
    @App
    DCCXApplication app;
    @ViewById
    TextView actionbar_title;
    @ViewById
    TextView back_icon;
    @ViewById
    TextView right_icon;
    @ViewById
    TextView tv_city;
    @ViewById
    TextView tv_cancel;
    @ViewById
    EditText et_selector_address;
    @ViewById
    ListView lv_list_address;
    @RestService
    IUsualAddressFinder finder;
    @Extra
    String flag;
    @Extra
    AddressList addressModel;
    Context context;
    private SearchAdapter searchAdapter;
    private AMapLocationClient mLocationClient = null;
    private AMapLocationClientOption mLocationOption = null;
    int requestCode;
    //标示，用户判断是否显示一次定位信息和用户重新定位
    private String city;
    List<HashMap<String, String>> searchList = new ArrayList<HashMap<String, String>>();

    @AfterViews
    void created() {
        actionbar_title.setText("常用地址");
        initIconfont();
        StatusBarCompat.setStatusBarColor(this, ContextCompat.getColor(this, R.color.colorActionbar));
        initLoc();
        a();

    }

    private void a() {
        et_selector_address.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int count, int after) {
                String content = s.toString().trim();
                InputtipsQuery inputtipsQuery = new InputtipsQuery(content, city);
                inputtipsQuery.setCityLimit(true);
                Inputtips inputtips = new Inputtips(CompileAddressActivity.this, inputtipsQuery);
                inputtips.setInputtipsListener(new Inputtips.InputtipsListener() {
                    @Override
                    public void onGetInputtips(List<Tip> list, int returnCode) {
                        if (returnCode == AMapException.CODE_AMAP_SUCCESS) {

                            for (int i = 0; i < list.size(); i++) {
                                HashMap<String, String> hashMap = new HashMap<String, String>();
                                hashMap.put("name", list.get(i).getName());//将地址信息取出放入HashMap中
                                hashMap.put("address", list.get(i).getAddress());
                                String[] a = list.get(i).getPoint().toString().split(",");
                                String jd = a[0];
                                String wd = a[1];
                                hashMap.put("longitude", jd);
                                hashMap.put("latitude", wd);

                                searchList.add(hashMap);//将HashMap放入表中
                            }
                            searchAdapter = new SearchAdapter(CompileAddressActivity.this, searchList);
                            lv_list_address.setAdapter(searchAdapter);
                            searchAdapter.notifyDataSetChanged();
                        }
                    }
                });
                inputtips.requestInputtipsAsyn();
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                searchList.clear();
            }
        });
    }

    private void initLoc() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(this);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次
        mLocationOption.setOnceLocation(false);
        //设置定位间隔
        //mLocationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    //定位回调
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                //定位成功回调
                aMapLocation.getLocationType();//获取当前定位结果来源
                aMapLocation.getLatitude();//获取纬度
                aMapLocation.getLongitude();//获取经度
                aMapLocation.getAccuracy();//获取精度信息
                aMapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
                aMapLocation.getCountry();//国家信息
                aMapLocation.getProvince();//省信息
                aMapLocation.getCity();//城市信息
                aMapLocation.getDistrict();//城区信息
                aMapLocation.getStreet();//街道信息
                aMapLocation.getStreetNum();//街道门牌号信息
                aMapLocation.getCityCode();//城市编码
                aMapLocation.getAdCode();//地区编码
                city = aMapLocation.getCity();
                tv_city.setText(city);
            }
        }
    }

    void initIconfont() {
        back_icon.setTypeface(app.iconfont);
        back_icon.setText(R.string.back_icon);
        right_icon.setVisibility(View.GONE);
    }

    @ItemClick
    void lv_list_address(int position) {
        Intent intent = getIntent();
        String addressType = intent.getStringExtra("address");
        setData(addressType, position);

    }

    private void setData(String addressType, int position) {
        String detailedaddress = searchList.get(position).get("name");
        String dulladdress = searchList.get(position).get("address");
        String city = "";
        String district = "";
        String addresstype = addressType;
        BigDecimal longitude = new BigDecimal(searchList.get(position).get("longitude"));
        BigDecimal latitude = new BigDecimal(searchList.get(position).get("latitude"));
        String province = "";
        RAddAddressModel rAddAddressModel = new RAddAddressModel();
        rAddAddressModel.setCity(city);
        rAddAddressModel.setAddresstype(addresstype);
        rAddAddressModel.setDistrict(district);
        rAddAddressModel.setDetailedaddress(detailedaddress);
        rAddAddressModel.setDulladdress(dulladdress);
        rAddAddressModel.setProvince(province);
        rAddAddressModel.setLongitude(longitude);
        rAddAddressModel.setLatitude(latitude);
        if (flag.equals("add")) {
            addAddress(rAddAddressModel);
        } else {
            updateAddress(rAddAddressModel, addressModel.getId());
        }
    }

    @Click
    void back_icon() {
        finish();
    }

    @Click
    void tv_cancel() {
        finish();
    }

    @Background
    void addAddress(RAddAddressModel model) {
        ResultModel<String> addAddress = finder.addAddress(model);
        showResout(addAddress);
    }

    @UiThread
    void showResout(ResultModel<String> addAddress) {
        if (addAddress != null) {
            if (addAddress.getErrno().equals("0")) {
                TastyToast.makeText(this, "添加常用地址成功", app.SHORT, app.SUCCESS);
                setResult(3);
                finish();
            } else {
                TastyToast.makeText(this, "添加常用地址失败", app.SHORT, app.ERROR);
            }
        }
    }

    @Background
    public void updateAddress(RAddAddressModel model, String id) {
        ResultModel<String> res = finder.updateAddress(model, id);
        show(res);
    }

    @UiThread
    void show(ResultModel<String> res) {
        if (res != null) {
            if (res.getErrno().equals("0")) {
                TastyToast.makeText(this, "修改常用地址信息成功", app.SHORT, app.SUCCESS);
                setResult(3);
                finish();
            } else {
                TastyToast.makeText(this, "修改常用地址信息失败", app.SHORT, app.ERROR);
            }
        }
    }
}
